package com.chuangke.sinotrukbudget.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chuangke.admin.model.SysDept;
import com.chuangke.admin.model.SysUserAuditDept;
import com.chuangke.admin.model.SysUserDataDept;
import com.chuangke.admin.service.SysDeptService;
import com.chuangke.admin.service.SysUserAuditDeptService;
import com.chuangke.admin.service.SysUserDataDeptService;
import com.chuangke.common.utils.SecurityUtils;
import com.chuangke.sinotrukbudget.service.BudgetAdminService;

@Service
public class BudgetAdminServiceImpl implements BudgetAdminService {
	
	@Autowired
	private SysDeptService sysDeptService;
	
	@Autowired
	private SysUserDataDeptService sysUserDataDeptService;
	
	@Autowired
	private SysUserAuditDeptService SysUserAuditDeptService ;

	@Override
	public List<SysDept> findUserEditDeptDetialData() {
		List<SysUserDataDept> userDataDeptList = sysUserDataDeptService.find(SecurityUtils.getUserId()) ;
		
		List<String> deptIdList = userDataDeptList.stream().map(SysUserDataDept::getDeptId).collect(Collectors.toList()) ;
		
		//不加载用户当前的所属组织机构
//		SysDept userDept = deptMap.get(sysUserService.findById(SecurityUtils.getUserId()).getDeptId()) ;
//		if(userDept != null) {
//			list.add(userDept) ;
//		}
		
		return getDeptByDeptId(deptIdList);
	}

	@Override
	public List<SysDept> findUserAuditDeptTreeData() {
		List<String> deptIdList = getUserAuditDeptDetail() ;
		return sysDeptService.findKinshipTree(deptIdList);
	}

	@Override
	public List<SysDept> findUserAuditDeptDetailData() {
		List<String> deptIdList = getUserAuditDeptDetail() ;
		return getDeptByDeptId(deptIdList);
	}
	
	private List<String> getUserAuditDeptDetail(){
		List<SysUserAuditDept> list = SysUserAuditDeptService.findByUserRole(SecurityUtils.getUserId()) ;
		List<SysUserDataDept> userDataDeptList = sysUserDataDeptService.find(SecurityUtils.getUserId()) ;
		List<String> deptIdList = new ArrayList<>() ;
		List<String> auditDeptIdList = list.stream().map(SysUserAuditDept::getDeptId).collect(Collectors.toList()) ;
		List<String> editDeptIdList = userDataDeptList.stream().map(SysUserDataDept::getDeptId).collect(Collectors.toList()) ;
		deptIdList.addAll(editDeptIdList) ;
		deptIdList.addAll(auditDeptIdList) ;
		return deptIdList ;
	}
	
	private List<SysDept> getDeptByDeptId(List<String> deptIdList){
		List<SysDept> list = new ArrayList<>() ;
		Map<String,SysDept> deptMap = sysDeptService.findMap() ;
		if(CollectionUtils.isEmpty(deptIdList)) {
			return list ;
		}
		
		deptIdList.forEach(deptId -> {
			SysDept ud = deptMap.get( deptId) ;
			if(ud != null) {
				list.add(ud) ;
			}
		});
		
		return list;
	}

}
